// src/hooks/useSendVerificationCode.ts
import type { Ref } from 'vue'
import { ref, watch } from 'vue'
interface UseSendVerificationCodeOptions {
  // 倒计时时间，单位为秒，默认为60秒
  countDownTime?: number
  // 按钮显示的文本，默认为"获取验证码"
  format?: string
  // 重试文本 默认为"%ds后重试"
  retryText?: string
  // 发送中文本 默认为"发送中"
  sendingText?: string
}

interface UseSendVerificationCodeReturn {
  // 按钮文本
  buttonText: Ref<string>
  // 按钮是否禁用
  isDisabled: Ref<boolean>
  // 发送验证码的函数
  sendVerificationCode: () => void
  // 重置发送按钮
  resetState: () => void
}

export function useSendVerificationCode(
  // 发送验证码的异步函数
  sendCode: () => Promise<void>,
  options: UseSendVerificationCodeOptions = {}
): UseSendVerificationCodeReturn {
  const countDownTime = options.countDownTime || 60
  const format = options.format || '获取验证码'
  const retryText = options.retryText || '%ds后重试'
  const sendingText = options.sendingText || '发送中'
  const interval = ref<any>()
  // 按钮的文本显示
  const buttonText = ref<string>(format)

  const isSending = ref(false)
  const isCountingDown = ref(false)
  const countDownSeconds = ref(countDownTime)

  // 发送验证码
  const sendVerificationCode = async () => {
    try {
      // 如果正在发送或正在倒计时中，则直接返回
      if (isSending.value || isCountingDown.value) {
        return
      }
      isSending.value = true
      buttonText.value = sendingText
      await sendCode()
      isSending.value = false
      countDownSeconds.value = countDownTime
      isCountingDown.value = true
    } catch (error) {
      isSending.value = false
      buttonText.value = format
      throw error
    }
  }

  // 重置按钮状态
  const resetState = () => {
    isSending.value = false
    isCountingDown.value = false
    buttonText.value = format
    clearInterval(interval.value)
    countDownSeconds.value = countDownTime
  }
  // 监听倒计时秒数，更新按钮显示的文本和禁用状态
  watch(countDownSeconds, val => {
    if (val > 0) {
      buttonText.value = retryText.replace('%d', String(val))
    } else {
      isCountingDown.value = false
    }
  })

  // 每秒减少1秒倒计时
  watch(
    isCountingDown,
    val => {
      if (val) {
        buttonText.value = retryText.replace(
          '%d',
          String(countDownSeconds.value)
        )
        interval.value = setInterval(() => {
          countDownSeconds.value -= 1
          if (countDownSeconds.value <= 0) {
            clearInterval(interval.value)
          }
        }, 1000)
      } else {
        buttonText.value = format
      }
    },
    { immediate: true }
  )

  // 按钮禁用状态
  const isDisabled = computed<boolean>(
    () => isSending.value || isCountingDown.value
  )
  return {
    buttonText,
    isDisabled,
    resetState,
    sendVerificationCode
  }
}
